package com.example.administrator.hqq.activity.home;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.MyGridView;
import com.example.administrator.hqq.View.RotateImage;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.activity.complain.ChatComplainActivity;
import com.example.administrator.hqq.adapter.module.GroupSettingGridAdater;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.base.MyApplication;
import com.example.administrator.hqq.bean.Complain;
import com.example.administrator.hqq.bean.GroupEvent;
import com.example.administrator.hqq.bean.group.GetGroupSettingsBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.google.gson.Gson;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import io.rong.push.RongPushClient;
import okhttp3.Call;

public class ChatRoomSettingActivity extends MyActivity {

    @BindView(R.id.return_auto)
    AutoLinearLayout returnAuto;
    @BindView(R.id.interference_image)
    ImageView interferenceImage;
    @BindView(R.id.group_member)
    MyGridView groupMember;
    @BindView(R.id.group_search)
    AutoLinearLayout groupSearch;
    @BindView(R.id.muted)
    Switch muted;
    @BindView(R.id.permission)
    Switch permission;
    @BindView(R.id.transfer)
    AutoRelativeLayout transfer;
    @BindView(R.id.quit)
    Button quit;
    @BindView(R.id.complain)
    AutoLinearLayout complain;
    @BindView(R.id.group_introduce)
    TextView groupIntroduce;
    @BindView(R.id.refresh_group)
    RotateImage refreshGroup;
    @BindView(R.id.refresh_auto)
    AutoRelativeLayout refreshAuto;
    @BindView(R.id.group_title)
    TextView groupTitle;
    @BindView(R.id.set_group_title)
    AutoLinearLayout setGroupTitle;
    @BindView(R.id.group_setting_guide)
    ImageView groupSettingGuide;
    private boolean isExecute = false;
    private List<GetGroupSettingsBean.DataBean.MemberBean> data;
    private String TAG = this.getClass().getSimpleName();
    private GroupSettingGridAdater groupSettingGridAdater;
    private GetGroupSettingsBean getGroupSettingsBean;
    private boolean is_quit=false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_room_setting);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initview();
        initdata();
    }

    private void initdata() {
        OkHttpUtils.get().url(UrlFactory.getGroupSettings()).tag(this)
                .addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.type, "1")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                Gson gson = new Gson();
                getGroupSettingsBean = gson.fromJson(response, GetGroupSettingsBean.class);
                if (getGroupSettingsBean.getCode() == 200) {
                    data.clear();
                    data.addAll(getGroupSettingsBean.getData().getMember());
                    groupSettingGridAdater.notifyDataSetChanged();
                    groupTitle.setText(getGroupSettingsBean.getGroup_title());
                    if (getGroupSettingsBean.getIs_muted() == 0) {
                        muted.setChecked(false);
                    } else {
                        interferenceImage.setVisibility(View.VISIBLE);
                        muted.setChecked(true);
                    }
                    if (getGroupSettingsBean.getChat_permission() == 0) {
                        permission.setChecked(false);
                    } else {
                        permission.setChecked(true);
                    }
                    isExecute = true;
                    for (GetGroupSettingsBean.DataBean.MemberBean datum : data) {
                        RongIM.getInstance().refreshUserInfoCache(new UserInfo(datum.getId(), datum.getName(), Uri.parse(datum.getUrl())));
                    }
                }
            }
        });
    }

    private void initview() {
        data = new ArrayList();
        groupSettingGridAdater = new GroupSettingGridAdater(data, this);
        if ("1".equals(getIntent().getStringExtra(LoongsConfig.group_member_type))) {
            boolean groupGuide = SPUtils.getInstance().getBoolean(LoongsConfig.groupGuide, true);
            if (groupGuide) {
                groupSettingGuide.setVisibility(View.VISIBLE);
                SPUtils.getInstance().put(LoongsConfig.groupGuide, false);
            }
            groupSettingGridAdater.setShowDeleteButton(true);

        } else {
            setGroupTitle.setVisibility(View.GONE);
            refreshAuto.setVisibility(View.GONE);
            groupIntroduce.setText("群聊信息");
            quit.setText("退出该群");
            transfer.setVisibility(View.GONE);
            complain.setVisibility(View.VISIBLE);
        }
        groupMember.setAdapter(groupSettingGridAdater);
        groupMember.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (groupSettingGridAdater.isShowDeleteButton() && data.size() == i) {
                    Intent intent = new Intent(ChatRoomSettingActivity.this, KickMemberActivity.class);
                    intent.putExtra(LoongsConfig.member, (Serializable) data);
                    intent.putExtra(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id));
                    startActivityForResult(intent, 30);
                } else {
                    addDirectchat(data.get(i).getId());
                }
            }
        });
        //设置消息免打扰
        muted.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                String s = "";
                if (b) {
                    s = "1";
                    interferenceImage.setVisibility(View.VISIBLE);
                    //false代表开启消息免打扰
                    LoongsConfig.getUsersIdSPUtils().put(getIntent().getStringExtra(LoongsConfig.group_id), false);
                    //设置会话提醒状态
                    RongIM.getInstance().setConversationNotificationStatus(Conversation.ConversationType.GROUP
                            , getIntent().getStringExtra(LoongsConfig.group_id), Conversation.ConversationNotificationStatus.DO_NOT_DISTURB, new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
                                @Override
                                public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {

                                }

                                @Override
                                public void onError(RongIMClient.ErrorCode errorCode) {

                                }
                            });
                } else {
                    //设置会话提醒状态
                    RongIM.getInstance().setConversationNotificationStatus(Conversation.ConversationType.GROUP
                            , getIntent().getStringExtra(LoongsConfig.group_id), Conversation.ConversationNotificationStatus.NOTIFY
                            , new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
                                @Override
                                public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {

                                }

                                @Override
                                public void onError(RongIMClient.ErrorCode errorCode) {

                                }
                            });
                    interferenceImage.setVisibility(View.GONE);
                    s = "0";
                    //true代表不开启消息免打扰
                    LoongsConfig.getUsersIdSPUtils().put(getIntent().getStringExtra(LoongsConfig.group_id), true);
                }
                Log.e("kang", "group_id: " + getIntent().getStringExtra(LoongsConfig.group_id));
                Log.e("kang", "是否: " + LoongsConfig.getUsersIdSPUtils().getBoolean(getIntent().getStringExtra(LoongsConfig.group_id)));
                if (isExecute)
                    setMuted(s);
            }
        });
        //设置私聊许可
        permission.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                String s = "";
                if (b) {
                    s = "1";
                } else {
                    s = "0";
                }
                if (isExecute)
                    setPermission(s);
            }
        });
    }

    /**
     * 创建私聊
     *
     * @param other_user_id
     */
    private void addDirectchat(final String other_user_id) {
        if (other_user_id.equals(LoongsConfig.getUser_id()))
            return;
        OkHttpUtils.get().url(UrlFactory.addDirectchat())
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.other_user_id, other_user_id)
                .addParams(LoongsConfig.type, "GROUP")
                .addParams(LoongsConfig.id, getIntent().getStringExtra(LoongsConfig.group_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    String description = jsonObject.getString(LoongsConfig.description);
                    HintWordsUtils.showMarkeWords(code, description);
                    if (code == 200) {
                        LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.Conversation.ConversationID, other_user_id);
                        SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).put(LoongsConfig.Conversation.ChatConversationType, LoongsConfig.Conversation.PRIVATE);
                        RongIM.getInstance().startConversation(ChatRoomSettingActivity.this, Conversation.ConversationType.PRIVATE, other_user_id, "");
                        Complain complain = new Complain(Complain.Type.DIRECTCHAT, "");
                        EventBus.getDefault().post(complain);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 设置消息免打扰
     *
     * @param muted 0表示关闭 1表示开启
     */
    public void setMuted(String muted) {
        OkHttpUtils.get().url(UrlFactory.setMuted()).tag(this)
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.value, muted)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "设置消息免打扰onError: " + e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "设置消息免打扰onResponse: " + response);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //当踢人完成后更新本地数据并刷新
        if (requestCode == 30 && resultCode == 50) {
            this.data.clear();
            this.data.addAll((List<GetGroupSettingsBean.DataBean.MemberBean>) data.getSerializableExtra(LoongsConfig.member));
            groupSettingGridAdater.notifyDataSetChanged();
        }
        //当转让完群主页面
        if (requestCode == 20 && resultCode == 110) {
            if (is_quit){
                quitGroup();
            }
            else{
                setResult(110);
                finish();
            }
        }
    }

    /**
     * 设置私聊许可
     *
     * @param permission 0表示不允许 1表示允许
     */
    public void setPermission(String permission) {
        OkHttpUtils.get().url(UrlFactory.setPermission())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.value, permission)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "设置私聊许可onError: " + e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "设置私聊许可onResponse: " + response);
            }
        });
    }

    @OnClick({R.id.group_setting_guide, R.id.set_group_title, R.id.group_search, R.id.transfer, R.id.quit, R.id.return_auto, R.id.complain, R.id.refresh_auto})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.group_setting_guide:
                groupSettingGuide.setVisibility(View.GONE);
                break;
            case R.id.set_group_title:
                if (getIntent().getStringExtra(LoongsConfig.group_member_type).equals("1")) {
                    Intent intent = new Intent(this, SettingGroupTitleActivity.class);
                    intent.putExtra(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id));
                    intent.putExtra(LoongsConfig.group_title, getGroupSettingsBean.getGroup_title());
                    startActivity(intent);
                }
                break;
            case R.id.group_search:
                //根据用户来判断是去设置还是查看页面
                if (getIntent().getStringExtra(LoongsConfig.group_member_type).equals("1")) {
                    Intent intent = new Intent(this, SettingGroupActivity.class);
                    intent.putExtra(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id));
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(this, SettingGroupActivity.class);
                    intent.putExtra(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id));
                    intent.putExtra(LoongsConfig.type, "member");
                    startActivity(intent);
                }
                break;
            case R.id.transfer:
                Intent intent1 = new Intent(this, TransferGroupActivity.class);
                intent1.putExtra(LoongsConfig.member, (Serializable) data);
                intent1.putExtra(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id));
                startActivityForResult(intent1, 20);
                break;
            case R.id.quit:
                if (getIntent().getStringExtra(LoongsConfig.group_member_type).equals("1")) {
                    if (data.size() == 1) {
                        AlertViewFactory.getInstance().showLeaveGroupReport(this, new AlertViewFactory.DeleteFriendReportOnclicke() {
                            @Override
                            public void submit(int position) {
                                quitGroup();
                            }

                            @Override
                            public void goComplain(int position) {
                                Log.e(TAG, "goComplain: " + LoongsConfig.ComplainType.GROUP.toString());
                                ChatComplainActivity.start(ChatRoomSettingActivity.this
                                        , RongPushClient.ConversationType.GROUP.toString()
                                        , getIntent().getStringExtra(LoongsConfig.group_id)
                                        , getIntent().getStringExtra(LoongsConfig.group_id)
                                        , LoongsConfig.ComplainType.QUIT_GROUP.toString());
                            }
                        });
                    } else {
                        Intent intent = new Intent(ChatRoomSettingActivity.this, TransferGroupActivity.class);
                        intent.putExtra(LoongsConfig.member, (Serializable) data);
                        intent.putExtra(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id));
                        is_quit=true;
                        startActivityForResult(intent, 20);
                    }
                } else {
                    AlertViewFactory.getInstance().showLeaveGroupReport(this, new AlertViewFactory.DeleteFriendReportOnclicke() {
                        @Override
                        public void submit(int position) {
                            quitGroup();
                        }

                        @Override
                        public void goComplain(int position) {
                            Log.e(TAG, "goComplain: " + LoongsConfig.ComplainType.GROUP.toString());
                            ChatComplainActivity.start(ChatRoomSettingActivity.this
                                    , RongPushClient.ConversationType.GROUP.toString()
                                    , getIntent().getStringExtra(LoongsConfig.group_id)
                                    , getIntent().getStringExtra(LoongsConfig.group_id)
                                    , LoongsConfig.ComplainType.QUIT_GROUP.toString());
                        }
                    });
                }
                break;
            case R.id.return_auto:
                finish();
                break;
            case R.id.complain:
                ChatComplainActivity.start(this, RongPushClient.ConversationType.GROUP.toString()
                        , getIntent().getStringExtra(LoongsConfig.group_id)
                        , getIntent().getStringExtra(LoongsConfig.group_id)
                        , LoongsConfig.ComplainType.GROUP.toString());
                break;
            case R.id.refresh_auto:
                refreshMyGroup();
                break;
        }
    }

    /**
     * 群聊置顶
     */
    private void refreshMyGroup() {
        refreshGroup.playAnimator();
        OkHttpUtils.get().url(UrlFactory.setGroupTop())
                .addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "置顶群聊onError: " + e.getMessage());
                if (refreshGroup != null) {
                    refreshGroup.stopAnimator();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "置顶群聊onResponse: " + response);
                if (refreshGroup != null) {
                    refreshGroup.stopAnimator();
                }
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    String description = jsonObject.getString(LoongsConfig.description);
                    HintWordsUtils.showMarkeWords(code, description);
                    if (code == 200) {
                        ToastUtils.showShort("置顶成功");
                        GroupEvent groupEvent = new GroupEvent();
                        groupEvent.setType(GroupEvent.Type.CREATE_GROUP);
                        EventBus.getDefault().post(groupEvent);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void quitGroup() {
        OkHttpUtils.get().url(UrlFactory.setActiveExit())
                .addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "退出群聊onError: " + e);
                ToastUtils.showShort("退出失败");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "退出群聊onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        ToastUtils.showShort("成功退出");
                        MyApplication.removeRongyunConversation(Conversation.ConversationType.GROUP, getIntent().getStringExtra(LoongsConfig.group_id));
                        GroupEvent groupEvent = new GroupEvent();
                        groupEvent.setType(GroupEvent.Type.DELETE_GROUP);
                        EventBus.getDefault().post(groupEvent);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Complain complain) {
        switch (complain.getType()) {
            case QUIT_GROUP:
                quitGroup();
                finish();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(GroupEvent groupEvent) {
        switch (groupEvent.getType()) {
            case ALTER_GROUP:
                initdata();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }

}
